<?php

namespace app\api\controller;


use app\adminapi\logic\InsurancePolicyLogic;
use app\api\validate\InsurancePolicyValidate;
use app\api\validate\PayValidate;
use app\common\libs\ImeiLib;
use app\common\model\Card;
use app\common\model\InsuranceOrder;
use app\common\model\InsurancePolicy;
use app\common\model\Model;
use app\common\model\Product;
use app\common\model\user\User;
use think\helper\Str;

class InsurancePolicyController extends BaseApiController
{

    public array $notNeedLogin = [];


    public function add()
    {
        $params = (new InsurancePolicyValidate())->post()->goCheck('add');
        $params['user_id'] = $this->userId;
        $user = User::findOrEmpty($this->userId);

        $InsurancePolicy = InsurancePolicyLogic::addUserInsurancePolicy($user, $params['imei'], $params['product_id'], $params['card_pwd'],
            $params['imgs'] ?? [], $params['contacts_name'], $params['contacts_phone'], $params['signImg']?? '');

        if (!$InsurancePolicy) {
            return $this->fail(InsurancePolicyLogic::getError());
        }
        $data = [
            'order_id' => (int)$InsurancePolicy->id,
            'from'     => 'InsurancePolicy'
        ];
        return $this->success('添加成功', $data);
    }


     public function items()
     {
         /**
          * @var User $user
          */
         $user = User::findOrEmpty($this->userId);

         $status = $this->request->param('status');
         $query = $user->insurancePolicyList()->with(['orderinfo'])->order('id desc');
         if ($status !=-1) {
             $query->where('status', $status);
         }else{
             $query->where('status', '<>', 0);
         }
         $type = (int) $this->request->param('type');
//         if ($type === 4){
//             $query->where('product_type_id', 4);
//         }else if ($type === 10){
//
//         }else{
//             $query->where('product_type_id', '<>', 4);
//         }
         $list = $query->paginate();
         return $this->success('获取成功', $list->toArray());
     }

     public function info()
     {
         $info = InsurancePolicy::findOrEmpty($this->request->param('id'));
         return $this->success('获取成功', $info->toArray());
     }

     public function savesignimg()
     {

         // 假设图片数据通过POST请求传递，并且存储在$_POST['image']中
         $base64Image = $this->request->param('image');

// 移除数据URI方案和基本标识
         $base64Image = preg_replace('#^data:image/\w+;base64,#i', '', $base64Image);

// 解码Base64字符串
         $imageData = base64_decode($base64Image);

         if (!is_dir(public_path().'signimg/')) {
             if (!mkdir($concurrentDirectory = public_path() . 'signimg/', 0777, true) && !is_dir($concurrentDirectory)) {
                 throw new \RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
             }
         }
         $uniqueId = md5(uniqid('', true));
         $fileName = public_path().'signimg/'. $uniqueId . '.png';
// 指定保存的文件名和路径

// 保存图片到文件
         file_put_contents($fileName, $imageData);
         return $this->success('保存成功', ['url' => request()->domain().'/signimg/'. $uniqueId . '.png']);
     }


     public function exchange()
     {

         $card_pwd = $this->request->param('card_pwd');
         $params = (new InsurancePolicyValidate())->post()->goCheck('exchange');

         $smsCode = $this->request->param('sms_code');
         /**
          * @var Card $card
          */
         $card = Card::where('account', $card_pwd)->find();
         if (!$card) {
             $this->fail('卡号不存在');
             return false;
         }

         $product_type_id = json_decode($card->product_id, true);
         if (!$product_type_id){
             $this->fail('该卡无产品');
         }
         // 找到产品和手机型号对应的产品ID
         try {
             $imeiRes = ImeiLib::search($params['imei'], ImeiLib::brand2Func($params['brand']));
         }catch (\Exception $e) {
             return $this->fail($e->getMessage());
         }

         $modelId = Model::where('spec', $imeiRes['spec'])->value('id');
         if (!$modelId) {
             return $this->fail('手机型号不存在');
         }

         $product_id_arr =  Product::whereIn('product_type_id',$product_type_id)->where('model_id',$modelId)->column('id');
         if (!$product_id_arr) {
             return $this->fail('未配置'.$imeiRes['spec'].'的产品');
         }

         $user = User::findOrEmpty($this->userId);
         $InsurancePolicy = InsurancePolicyLogic::addUserInsurancePolicy($user, $params['imei'], $product_id_arr, $params['card_pwd'],
             $params['imgs'] ?? [], $params['contacts_name'], $params['contacts_phone'], $params['signImg']?? '');
         if (!$InsurancePolicy){
             return  $this->fail(InsurancePolicyLogic::getError());
         }
         $InsurancePolicy->pay_status = 1;
         $InsurancePolicy->pay_type = 2;
         $InsurancePolicy->pay_time = date('Y-m-d H:i:s');

         $InsurancePolicy->save();

         InsurancePolicyLogic::apply($InsurancePolicy->id,1);

         return $this->success('兑换成功',['order'=>$InsurancePolicy]);


     }



}